package org.example.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.example.entity.RepayPlan;
import org.example.mapper.RepayPlanMapper;
import org.example.service.IRepayPlanService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 还款计划表 服务实现类
 * </p>
 *
 * @author libo
 * @since 2023-11-20
 */
@Service
@DS("fms")
public class RepayPlanServiceImpl extends ServiceImpl<RepayPlanMapper, RepayPlan> implements
        IRepayPlanService {

    @Override
    public List<RepayPlan> listByIdsWithTable(Collection<? extends Serializable> idList,
            String tableNames) {
        return baseMapper.listByIdsWithTable(idList, tableNames);
    }

    @Override
    public List<RepayPlan> actualNodeRepayDay(String tableName, Date startTime, Date endTime,
            List<String> deductChannels, Long processMaxId, Long batchRecodeSize) {
        return getBaseMapper().actualNodeRepayDay(tableName, startTime, endTime, deductChannels,
                processMaxId, batchRecodeSize);
    }

    /**
     * 根据 ID 选择修改
     *
     * @param entity 实体对象
     */
    public boolean updateById(RepayPlan entity) {
        if (StringUtils.isNoneBlank(entity.getOtherpayBatch())) {
            UpdateWrapper<RepayPlan> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", entity.getId());
            wrapper.eq("otherpay_batch", entity.getOtherpayBatch());
            return SqlHelper.retBool(getBaseMapper().update(entity, wrapper));
        } else {
            return SqlHelper.retBool(getBaseMapper().updateById(entity));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateBatchById(Collection<RepayPlan> entityList, int batchSize) {
        String sqlStatement = "org.example.mapper.RepayPlanMapper.updateByIdAndOtherpayBatch";
        return executeBatch(entityList, batchSize, (sqlSession, entity) -> {
            MapperMethod.ParamMap<RepayPlan> param = new MapperMethod.ParamMap<>();
            param.put(Constants.ENTITY, entity);
            sqlSession.update(sqlStatement, param);
        });
    }

    @Transactional
    @Override
    public void saveTrans(RepayPlan rp2) {
        this.save(rp2);
    }
}
